package cn.ffcs.businessrequest.web;


import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import com.opensymphony.xwork2.ActionContext;

import cn.ffcs.base.web.BaseAction;
import cn.ffcs.bpm.model.DocumentType;
import cn.ffcs.bpm.service.DocumentTypeService;
import cn.ffcs.businessrequest.model.BusinessRequest;
import cn.ffcs.businessrequest.model.ReqDocu;
import cn.ffcs.businessrequest.service.ReqDocuService;
import cn.ffcs.security.model.User;
import cn.ffcs.util.MyList;
import cn.ffcs.util.context.ApplicationContextUtil;

/**
 * 
 * 业务需求交互单action层，实现页面业务逻辑<br/> <table>
 * <tr>
 * <td>负责人/principal: </td>
 * <td colspan="2">pany</td>
 * <tr>
 * <td>修改记录/revision:</td>
 * <td colspan="2"></td>
 * </tr>
 * <tr>
 * <td>日期:</td>
 * <td>修改人:</td>
 * <td>修改说明:</td>
 * </tr>
 * <tr>
 * <td></td>
 * <td></td>
 * <td></td>
 * </tr>
 * </table>
 * @author pany
 * @version $Id$
 */
public class ReqDocuAction<P extends ReqDocu> extends BaseAction<P>
{
    /** 业务POJO **/
    private P reqDocu;
    /** 节点id **/
    private String processDetailId;
    /** 需求单id **/
    private String businessRequestId;
    /** 保存后文档id **/
    private String docIds;
    /** 文档服务 **/
    private ReqDocuService reqDocuService;
    /** 文档类型服务 **/
    private DocumentTypeService documentTypeService;
    /** 文档类型实例 **/
    private List<DocumentType> documentTypes;
    /** 文档实例 **/
    private List<P> reqDocus;
    /** 文档实例 **/
    private List<P> curReqDocus;
    /** 文档上传 **/
    private List<File> uploads;
    /** 上传文档名称 **/
    private List<String> fileNames;
    /** 上传文档名称 **/
    private List<String> uploadContentTypes;
    /** 文档类型 **/
    private List<String> docTypeIds;
    /** 其他附件上传 **/
    private List<File> otherFiles;
    
    
    
    /**
     * 根据关键值获取实体数据
     * @return
     */
    public String findById()
    {
        if (reqDocu != null && reqDocu.getId() != 0)
        {
            reqDocu = (P) baseService.findById(reqDocu.getId());
        }
        return SUCCESS;
    }

    /**
     * 文件上传
     * @return
     * @throws Exception
     */
    public String uploadDocument(){
        if(processDetailId!=null&&!"".equals(processDetailId)){
            Criterion cond = Restrictions.eq("processDetail.id", new Integer(processDetailId));
            documentTypes = documentTypeService.findBy(cond);
            if(businessRequestId!=null&&!"".equals(businessRequestId)){
                Criterion cond1 = Restrictions.eq("refEntity", new BusinessRequest()
                        .getClass().getName());
                Criterion cond2 = Restrictions.eq("refEntityId", businessRequestId);
                Criterion cond3 = Restrictions.eq("processDetail.id", new Integer(processDetailId));
                Criterion cond4 = Restrictions.and(cond1, cond2);
                Criterion condDocu = Restrictions.and(cond3, cond4);
                curReqDocus = baseService.findBy(condDocu);
            }else if(docIds!=null&&docIds.length()>1){
                String[] reqDocuIds =docIds.substring(1).split(",");
                Criterion condDocu =Restrictions.in("id", reqDocuIds);
                curReqDocus = baseService.findBy(condDocu);
            }
        }
        return SUCCESS;
    }

    /**
     * 文件上传
     * @return
     * @throws UnsupportedEncodingException 
     * @throws Exception
     */
    public String saveReqDocu() throws UnsupportedEncodingException{
        if (processDetailId != null && !"".equals(processDetailId))
        {
            if ((docTypeIds == null && uploads == null) || (uploads.size() == docTypeIds.size()))
            {
                String[] reqDocuIDs = getContextObjects("reqDocuIDs");
                // 删除附件
                String[] delIDs = getContextObjects("delIDs");
                // 保存数据
                docIds=reqDocuService.saveReqDocu(businessRequestId, processDetailId,
                        docTypeIds, uploads, fileNames, reqDocuIDs, delIDs, otherFiles);
                
            }
        }
        return SUCCESS;
    }
    
    /**
     * 需求单提交时，判断需要上传的文档类型是否都上传；必须都上传才可提交需求单
     * @return
     */
    public boolean isCompleteDocument(String processDetailId,String businessRequestId,String docId) {
        Criterion cond = Restrictions.eq("processDetail", processDetailId);
        documentTypes = documentTypeService.findBy(cond);
        if(documentTypes==null||documentTypes.size()==0){
            return true;
        }
        ///需求单未创建时，判断
        if (businessRequestId != null && !"".equals(businessRequestId)){
            if(docId!=null&&docId.length()>1){
                docId=docId.substring(1);
                String []docIds= docId.split(",");
//                boolean flag=false;
                if(docIds!=null&&docIds.length>0&&documentTypes.size()==docIds.length)
                    return true;
            }
        }else{
            Criterion cond1 = Restrictions.eq("refEntity", new BusinessRequest()
                .getClass().getName());
            Criterion cond2 = Restrictions.eq("refEntityId", businessRequestId);
            Criterion cond3 = Restrictions.eq("processDetail", processDetailId);
            Criterion cond4 = Restrictions.and(cond1, cond2);
            Criterion condDocu = Restrictions.and(cond4, cond3);
            curReqDocus = baseService.findBy(condDocu);
            if(curReqDocus!=null&&curReqDocus.size()>0&&documentTypes.size()==curReqDocus.size())
                return true;
        }
        return false;
    }
    
    
    public boolean compareDocType(){
        boolean flag=false;
        for(int i=0;i<documentTypes.size();i++){
            flag=false;
            String docType=documentTypes.get(i).getDocType()+"";
            for(int j=0;j<curReqDocus.size();j++){
                if(docType.equals(curReqDocus.get(j).getDocType())){
                    flag=true;
                    break;
                }
            }
            if(!flag)
                return flag;
        }
        
        return true;
    }
    
    /**
     * 文件下载
     * @return
     * @throws Exception
     */
    public String showDocu() throws Exception
    {
        findById();
        String fileName = reqDocu.getFullName();
        ActionContext ctx = ActionContext.getContext();
        HttpServletResponse response = (HttpServletResponse) ctx
                .get(ServletActionContext.HTTP_RESPONSE);
        response.setContentType("application/x-download");//设置为下载application/x-download
        response.setHeader("Content-Disposition", "attachment;filename="
                + new String(fileName.getBytes("GBK"), "iso8859-1"));
        if(reqDocu.getContent()!=null&&reqDocu.getContent().getContent()!=null)
            write(response.getOutputStream(), reqDocu.getContent().getContent());
        return null;
    }

    
    
    /**
     * 输出文件内容
     * @param os
     * @param content
     */
    private void write(OutputStream os, byte[] content)
    {
        try
        {
            os.write(content);
            os.flush();
        }
        catch (IOException ex)
        {
            throw new RuntimeException(ex);
        }
    }
    
    public P getReqDocu()
    {
        return reqDocu;
    }

    public void setReqDocu(P reqDocu)
    {
        this.reqDocu = reqDocu;
    }

    public String getBusinessRequestId()
    {
        return businessRequestId;
    }

    public void setBusinessRequestId(String businessRequestId)
    {
        this.businessRequestId = businessRequestId;
    }

    public String getProcessDetailId()
    {
        return processDetailId;
    }

    public void setProcessDetailId(String processDetailId)
    {
        this.processDetailId = processDetailId;
    }

    public List<DocumentType> getDocumentTypes()
    {
        return documentTypes;
    }

    public void setDocumentTypes(List<DocumentType> documentTypes)
    {
        this.documentTypes = documentTypes;
    }

    public DocumentTypeService getDocumentTypeService()
    {
        return documentTypeService;
    }

    public void setDocumentTypeService(DocumentTypeService documentTypeService)
    {
        this.documentTypeService = documentTypeService;
    }

    public List<P> getReqDocus()
    {
        return reqDocus;
    }

    public void setReqDocus(List<P> reqDocus)
    {
        this.reqDocus = reqDocus;
    }

    public List<P> getCurReqDocus()
    {
        return curReqDocus;
    }

    public void setCurReqDocus(List<P> curReqDocus)
    {
        this.curReqDocus = curReqDocus;
    }
    public List<String> getUploadContentTypes()
    {
        return uploadContentTypes;
    }

    public void setUploadContentTypes(List<String> uploadContentTypes)
    {
        this.uploadContentTypes = uploadContentTypes;
    }

    public List<File> getUpload()
    {
        return uploads;
    }

    public void setUpload(List<File> uploads)
    {
        this.uploads = uploads;
    }

    public List<String> getUploadFileName()
    {
        return fileNames;
    }

    public void setUploadFileName(List<String> fileNames)
    {
        this.fileNames = fileNames;
    }

    public List<String> getDocTypeId()
    {
        return docTypeIds;
    }

    public void setDocTypeId(List<String> docTypeIds)
    {
        this.docTypeIds = docTypeIds;
    }

    public ReqDocuService getReqDocuService()
    {
        return reqDocuService;
    }

    public void setReqDocuService(ReqDocuService reqDocuService)
    {
        this.reqDocuService = reqDocuService;
    }

    public String getDocIds()
    {
        return docIds;
    }

    public void setDocIds(String docIds)
    {
        this.docIds = docIds;
    }

    public List<String> getDocTypeIds()
    {
        return docTypeIds;
    }

    public List<File> getOtherFile()
    {
        return otherFiles;
    }

    public void setOtherFile(List<File> otherFiles)
    {
        this.otherFiles = otherFiles;
    }
    
}
